rei_ros.linkMaster = function (ROS_IP = '192.168.8.1') {
    lamp = document.getElementById('slam-lamp')
    try{
        var ros = new ROSLIB.Ros({
            url : 'ws://'+ROS_IP+':9090'
        });
        // ros_is_linked = false
        // 检查连接状态
        ros.on('connection', function () {
            console.log('Connected to ROS');
            reconnectCount = 0;
            ros_is_linked = true;
            rei_ros.add_keyboardToHtml({
                ros:ros,
                is_open:true,
            });
            lamp.style.backgroundImage = "url('static/img/slam-car-green.svg')";
        });
    
        ros.on('error', function (error) {
            console.log('Error connecting to ROS: ' + error);
            ros_is_linked = false;
            // lamp.style.backgroundColor = "#ff0202";
            rei_ros.add_keyboardToHtml({
                ros:ros,
                is_open:false,
            });
            lamp.style.backgroundImage = "url('static/img/slam-car-rad.svg')";
        });
    
        ros.on('close', function () {
            console.log('Connection to ROS closed');
            ros_is_linked = false;
            // lamp.style.backgroundColor = "#ff0202";
            rei_ros.add_keyboardToHtml({
                ros:ros,
                is_open:false,
            });
            lamp.style.backgroundImage = "url('static/img/slam-car.svg')"
        });
        return ros
    } catch (e) {
        console.log(e)
    }
}

function showPopup(Id){
    // 获取弹窗元素
    var popup = document.getElementById(Id);
    var close_button = popup.querySelector('.rei-close-window-button')
    close_button.onclick = function () {
        popup.style.visibility = 'hidden';
    };
    // 获取窗口宽度和高度
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    // 获取弹窗自身宽度和高度
    var popupWidth = popup.offsetWidth;
    var popupHeight = popup.offsetHeight;

    // 计算弹窗在水平和垂直方向上的居中位置
    var x = (windowWidth - popupWidth) / 2;
    var y = (windowHeight - popupHeight) / 2;

    // 设置弹窗的位置
    popup.style.left = x + 'px';
    popup.style.top = y + 'px';

    // 显示弹窗
    popup.style.visibility = 'visible';
}

function addDropDown(id,options) {
    const DropDown = document.getElementById(id);
    DropDown.classList.add('DropDown');
    const DropDown_list = document.createElement('div')
    DropDown_list.classList.add('DropDown-list')
    options = options || {};
    var text_len=4;
    for(const key in options){
        var new_span = document.createElement('span');
        new_span.id = key;
        if (text_len < options[key].length){
            text_len = options[key].length
        }
        new_span.textContent = options[key];
        new_span.classList.add('DropDown-button');
        DropDown_list.appendChild(new_span)
    }
    DropDown_list.style.width = (text_len*16+10) + 'px';
    DropDown.appendChild(DropDown_list)
    DropDown.style.cursor = 'pointer';
}

function addTips(id,tip_txt){
    const tip = document.getElementById(id)
    const tipTxt = document.createElement('span')
    tip.classList.add('tips');
    tipTxt.classList.add('tips-txt');
    tipTxt.style.width = (tip_txt.length*12) + 'px';
    tipTxt.textContent = tip_txt
    tip.appendChild(tipTxt)
}

var reinovo = io.connect('http://192.168.8.1:5000');
var ros = rei_ros.linkMaster('127.0.0.1')

var rviz = new rei_viewer({
    ros:ros,
    scan_topic:'/fuse_scan',
    divID:'slam_viewer_rviz'
})
let robotData = {}

reinovo.on('RobotData_response', function (data) {
    robotData = data
    // const log_window = document.getElementById('log-output')
    // console.log(data)
    // var log_output = log_window.querySelector('.rei-window-output')
    // log_output.textContent = ''
    // robotHistory.log.forEach(line => {
    //     const textNode = document.createTextNode(line);
    //     log_output.appendChild(textNode);
    //     const brNode = document.createElement('br')
    //     log_output.appendChild(brNode)
    // })
    reinovo.emit('RobotData',{})
});

reinovo.emit('RobotData',{})

function rei_log(msg) {
    console.log(msg);
    time = String(new Date())
    var list = time.split(' ')
    reinovo.emit('RobotData',{'log' :list[0]+' '+list[1]+' '+list[2]+' '+list[4]+' '+list[3]+'[INFO]' + msg})
};

reinovo.on('reinovo_response', function (log) {
    var data = log.time+"["+log.level+"]"+log.msg;
    console.log(data);
    reinovo.emit('RobotData',{'log' :data})
    reinovo.emit('reinovo_log','test');
});

var inter = 0
const intervalId = setInterval(function () {
    rei_log('获取机器人信息中')
    if (typeof robotData['robot_ID'] != 'undefined'){
        try{
            rei_robot = new rei_robot_slam_core({robotName:robotData['robot_ID']})
            console.log('识别到'+ robotData['robot_ID'])
        }catch(error){
            console.log('未能识别到设备')
        }
        //增加新的设备
        // rei_log('识别到设备:'+robotData['robot_ID'])
        clearInterval(intervalId)
        // mapList.forEach(map=>{
        //     var newoption = new Option(map,map)
        //     selectElement.appendChild(newoption)
        // })
        // 加载界面
        $(".loader-wrapper").fadeOut("slow")
    }else{
        rei_log('未查询到机器人信息')
        inter++
        rei_log('一秒后进行第'+inter+'次尝试')
    }
}, 500); // 每隔2秒执行一次

function close_all_tab(){
    $("#rei-make-map-tab").hide();
    $("#rei-edit-map-tab").hide();
    $("#rei-edit-map-param-tab").hide();
    $("#rei-robot-data-tab").hide();
}
close_all_tab();
$("#rei-make-map-tab").show()
$("#rei-make-map").click(function () {
    close_all_tab();
    $("#rei-make-map-tab").fadeIn("slow")
});
$("#rei-edit-map").click(function () {
    close_all_tab();
    $("#rei-edit-map-tab").fadeIn("slow")
});
$("#rei-edit-map-param").click(function () {
    close_all_tab();
    $("#rei-edit-map-param-tab").fadeIn("slow")
});
$("#rei-robot-data").click(function () {
    close_all_tab();
    $("#rei-robot-data-tab").fadeIn("slow")
});

function slamInit() {
    rviz.stop()
    ros = rei_ros.linkMaster('127.0.0.1')
    setTimeout(function () {
        rviz = new rei_viewer({
            ros:ros,
            scan_topic:'/fuse_scan',
            cameraPose:{x:0,y:0,z:10},
            divID:'slam_viewer_rviz'
        })
        // rviz.updata()
    }, 9000);
}
slamInit()

window.onresize = function() {
    rviz.resize()
};

const slam_start = document.getElementById('start_slam')
slam_start.onclick = function () {
    if(ros_is_linked==true){
        new showPopup('stop-slam')        
    }else{
        $.ajax({
            url: "/startSlam",
            type: "POST",
            data: {
                'cmd':'open',
            },
            success: function(response){
                console.log(response.mssage)
                slamInit()
            },
            error: function (xhr, status, error) {
                console.log("出错啦: " + error);
            }
        });    
    }
}

function stop_slam(){
    var popup = document.getElementById('stop-slam')
    popup.style.visibility = 'hidden';
    $.ajax({
        url: "/startSlam",
        type: "POST",
        data: {
            'cmd':'close',
        },
        success: function(response){
            console.log(response.mssage)
            slamInit()
        },
        error: function (xhr, status, error) {
            console.log("出错啦: " + error);
        }
    });  
}


const slam_map_save = document.getElementById('map_save')
slam_map_save.onclick = function () {
    if(ros_is_linked == true){
        new showPopup('map_save_window')
    }else{
        alert('地图构建未开启')
    }
}

const save_map = document.getElementById('map-save-start')
save_map.onclick = function() {
    var getmapname = document.getElementById('map-name').value
    $.ajax({
        url: "/saveSlam",
        type: "POST",
        data: {
            'cmd':'open',
            'map_name': getmapname,
        },
        success: function(response){
            console.log(response.mssage)
            alert(response.mssage)
        },
        error: function (xhr, status, error) {
            console.log("出错啦: " + error);
        }
    });
}